<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="购物清单" name="first">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="物资名称" prop="materialId">
            <el-select v-model="queryParams.materialId" filterable placeholder="请选择">
              <el-option
                v-for="item in materialOptions"
                :key="item.materialId"
                :label="item.materialName"
                :value="item.materialId">
                <span style="float: left">{{ item.applicationType }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单价" prop="price">
            <el-input
              v-model="queryParams.price"
              placeholder="请输入单价"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="数量" prop="quantity">
            <el-input
              v-model="queryParams.quantity"
              placeholder="请输入数量"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="daterangeCreateTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="总价" prop="total">
            <el-input
              v-model="queryParams.total"
              placeholder="请输入总价"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['trade:material:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['trade:material:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['trade:material:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['trade:material:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="序号" align="center" type="index"/>
          <el-table-column label="应用类型" align="center" prop="applicationType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.basic_material_application_type" :value="scope.row.applicationType"/>
            </template>
          </el-table-column>
          <el-table-column label="物资类型" align="center" prop="materialTypeName"/>
          <el-table-column label="物资名称" align="center" prop="materialName"/>
          <el-table-column label="数量" align="center" prop="quantity"/>
          <el-table-column label="单价" align="center" prop="price"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>

          <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.updateTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center" prop="total"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['trade:material:edit']"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['trade:material:remove']"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改物资交易管理对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="物资名称" prop="managerId">
              <el-select v-model="form.materialId" filterable placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in materialOptions"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId">
                  <span style="float: left">{{ item.materialTypeName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.materialName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入数量"/>
            </el-form-item>
            <el-form-item label="单价" prop="price">
              <el-input v-model="form.price" placeholder="请输入单价"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="使用记录" name="second">
        <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>

          <el-table-column label="应用类型" align="center" prop="applicationType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.basic_material_application_type" :value="scope.row.applicationType"/>
            </template>
          </el-table-column>
          <el-table-column label="物资类型" align="center" prop="materialTypeName"/>
          <el-table-column label="物资名称" align="center" prop="materialName"/>
          <el-table-column label="数量" align="center" prop="quantity"/>
          <el-table-column label="使用人" align="center" prop="userName"/>
          <el-table-column label="岗位" align="center" prop="postName"/>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
      <el-tab-pane label="剩余情况" name="third">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
          <el-form-item label="应用类型" prop="applicationType">
            <el-select v-model="queryParams.applicationType" placeholder="请选择应用类型" clearable>
              <el-option
                v-for="dict in dict.type.basic_material_application_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物资类型" prop="materialTypeName">
            <el-input
              v-model="queryParams.materialTypeName"
              placeholder="请输入物资类型"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="物资名称" prop="materialName">
            <el-input
              v-model="queryParams.materialName"
              placeholder="请输入物资类型"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="编号" align="center" prop="materialId" />
          <el-table-column label="应用类型" align="center" prop="applicationType" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.basic_material_application_type" :value="scope.row.applicationType" />
            </template>
          </el-table-column>
          <el-table-column label="物资类型" align="center" prop="materialTypeName"/>
          <el-table-column label="数量" align="center" prop="quantity"/>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  listMaterial,
  getMaterial,
  delMaterial,
  addMaterial,
  updateMaterial,
  listMaterialUsage, listMaterialStore
} from "@/api/trade/material";

export default {
  name: "Material",
  dicts: ['basic_material_application_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      materialOptions: [],
      // 物资交易管理表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      activeName: 'first',
      // 是否显示弹出层
      open: false,
      // 总价时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialId: null,
        quantity: null,
        price: null,
        createTime: null,
        total: null,
        params: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialId: [
          {required: true, message: "物资id不能为空", trigger: "change"}
        ],
        quantity: [
          {required: true, message: "数量不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "单价不能为空", trigger: "blur"}
        ],
        total: [
          {required: true, message: "总价不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物资交易管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.activeName === 'first') {
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        } else {
          this.queryParams.params["beginCreateTime"] = '';
          this.queryParams.params["endCreateTime"] = '';
        }
        getMaterial(null).then(response => {
          this.materialOptions = response.data.materialList;
        });
        listMaterial(this.queryParams).then(response => {
          this.materialList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else if (this.activeName === 'second') {
        listMaterialUsage(this.queryParams).then(response => {
          this.materialList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }else if(this.activeName === 'third'){
        listMaterialStore(this.queryParams).then(response => {
          this.materialList= response.rows;
          console.log(this.materialList)
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // this.form = {
      //   orderId: null,
      //   materialId: null,
      //   quantity: null,
      //   price: null,
      //   createTime: null,
      //   total: null,
      //   createBy: null
      // };
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      getMaterial(null).then(response => {
        this.form = response.data;
        this.materialOptions = response.data.materialList;
        this.open = true;
        this.title = "添加物资交易管理";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const orderId = row.orderId || this.ids
      getMaterial(orderId).then(response => {
        this.form = response.data;
        this.materialOptions = response.data.materialList;
        this.open = true;
        this.title = "修改物资交易管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.orderId != null) {
            this.form.createTime = null;
            this.form.updateTime = null;
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除物资交易管理编号为"' + orderIds + '"的数据项？').then(function () {
        return delMaterial(orderIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('trade/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    },
    handleClick(tab, event) {
      this.reset()
      if (tab.name === 'first') {
        this.activeName = 'first'
      }else if (tab.name === 'second') {
        this.activeName = 'second'
      }else if(tab.name === 'third'){
        this.activeName = 'third'
      }
      this.queryParams ={
        pageNum: 1,
          pageSize: 10,
          materialId: null,
          quantity: null,
          price: null,
          createTime: null,
          total: null,
          params: null,
      };
      this.getList()
    }
  }
};
</script>
